package mvc.unti;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mvc.form.XmlBean;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class StrutsXml {

	public static Map<String, XmlBean> struts_xml(String path) {
		SAXBuilder builder = new SAXBuilder();
		try {
			Document document = builder.build(new File(path));
			Element root = document.getRootElement();
			Map<String, XmlBean> rmap = new HashMap<String, XmlBean>();
			/**
			 * 获得xml中的action-mappings
			 */
			List<Element> mappings = root.getChild("action-mappings").getChildren();
			for (Element mapping : mappings) {
				XmlBean xmlBean = new XmlBean();
				String actionName = mapping.getAttributeValue("name");
				xmlBean.setBeanName(actionName);
				/**
				 * 获得xml中的form-beans
				 */
				List<Element> beans = root.getChild("form-beans").getChildren();
				for (Element bean : beans) {
					String beanName = bean.getAttributeValue("name");
					if (actionName.equals(beanName)) {
						String beanClass = bean.getAttributeValue("class");
						xmlBean.setBeanClass(beanClass);
						break;
					}
				}

				String actionpPath = mapping.getAttributeValue("path");
				String actionClass = mapping.getAttributeValue("class");
				xmlBean.setActionpPath(actionpPath);
				xmlBean.setActionClass(actionClass);

				List<Element> forward = mapping.getChildren();
				Map<String, String> map = new HashMap<String, String>();
				for (Element f : forward) {
					String fname = f.getAttributeValue("name");
					String fvalue = f.getAttributeValue("value");
					map.put(fname, fvalue);
				}
				xmlBean.setActionForward(map);
				rmap.put(actionpPath, xmlBean);
			}
			return rmap;
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

	public static void struts_xml() {
		SAXBuilder builder = new SAXBuilder();
		try {
			Document document = builder.build(new File("/struts.xml"));
			Element root = document.getRootElement();
			/**
			 * 获得xml中的beans
			 */
			List<Element> beans = root.getChild("beans").getChildren();
			for (Element e : beans) {
				String name = e.getAttributeValue("name");
				String clazz = e.getAttributeValue("class");
			}
			/**
			 * 获得xml中的actions
			 */
			List<Element> actions = root.getChild("actions").getChildren();
			for (Element e : actions) {
				String path = e.getAttributeValue("path");
				String name = e.getAttributeValue("name");
				String clazz = e.getAttributeValue("class");
				List<Element> forward = e.getChildren();
				for (Element f : forward) {
					String fname = f.getAttributeValue("name");
					String fvalue = f.getAttributeValue("value");
				}
			}

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
